package com.aglhz.nature.view;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.aglhz.base.BaseActivity;
import com.aglhz.nature.R;
import com.aglhz.nature.utils.Constants;
import com.aglhz.nature.utils.MD5;
import com.aglhz.nature.view.HomeShowWebActivity.JavaScriptObject;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;

public class NatureLifeWebActivity extends BaseActivity{
	private WebView columnsWebView;
	private String url;
	private SharedPreferences sharedPreferences;
	private String token;
	private String nor_token;
	private String wx_token;
	private IWXAPI api;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	setContentView(R.layout.columnslistweb);
	setActionBarTitle("自然生活");
	columnsWebView=(WebView) findViewById(R.id.columnsWebView);
	api = WXAPIFactory.createWXAPI(getApplication(), Constants.WX_KEY);
	//获取sharedPreferences里面的信息,微信
			sharedPreferences =getSharedPreferences("WX_INFO", Context.MODE_PRIVATE);
			wx_token=sharedPreferences.getString("token", "");
			//获取sharedPreferences里面的信息,普通登陆
			sharedPreferences = getSharedPreferences("Normal_Info",Context.MODE_PRIVATE);
			nor_token=sharedPreferences.getString("NORMAL_Token", "");
			if(!(""==wx_token)){
				token=wx_token;
			}else{
				token=nor_token;
			}
	Intent intent=getIntent();
	url = intent.getStringExtra("NatureLifeWebActivity");
		
	WebSettings webSettings = columnsWebView.getSettings();  
    //设置WebView属性，能够执行Javascript脚本    
    webSettings.setJavaScriptEnabled(true);    
    //设置可以访问文件  
    webSettings.setAllowFileAccess(true);  
  //webview自适应屏幕
    webSettings.setUseWideViewPort(true); 
    webSettings.setLoadWithOverviewMode(true); 

    columnsWebView.loadUrl(url+"?token="+token+"&appType=2");    
    Log.i("url",  url+"&token="+token+"&appType=2");
   
    //设置Web视图  
   
    columnsWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
       
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        	
        	super.onPageStarted(view, url, favicon);
     
        
    	
        }
        
        @Override
		public void onPageFinished(WebView view, String url) {
			
			super.onPageFinished(view, url);
			

		}
    });
 
    columnsWebView.addJavascriptInterface(new JavaScriptObject(NatureLifeWebActivity.this),"android"); 
		
	}
	public class JavaScriptObject {
		 Context mContext;

		public JavaScriptObject(Context mContext) {
			super();
			this.mContext = mContext;
		}
		 
		@JavascriptInterface
		 public void loadHomePage() {
		
			Intent intent =new Intent(NatureLifeWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_HOME_TAG;
			startActivity(intent);
			finish();
		} 
		@JavascriptInterface
		 public void goToShoppingCart() {
			Intent intent =new Intent(NatureLifeWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_SHOPCART_TAG;
			startActivity(intent);
			finish();
			
		} 
		
		@JavascriptInterface
		public void appLoginFunc(){
			Intent intent =new Intent (NatureLifeWebActivity.this,LoginActivity.class);
			startActivity(intent);
		}
		@JavascriptInterface
		 public void appWeixinPay(String a) {

			

			sharedPreferences =getSharedPreferences("PAY", Context.MODE_PRIVATE);
			sharedPreferences.edit().clear();
			sharedPreferences.edit().putString("PAYINFO", a).commit();
			JSONObject json;
			try {
				json = new JSONObject(a);
				JSONObject payData = json.getJSONObject("data");
				Log.e("json",json.toString());
				
				if(json == null)
					return;
				
				
				PayReq req = new PayReq();
				
				req.appId =payData.getString("appId");
				Log.e("appId",req.appId);
				req.partnerId = payData.getString("partnerid");
				Log.e("partnerId",req.partnerId);
				req.prepayId=  payData.getString("prepayid");
				Log.e("prepayId",req.prepayId);
				req.packageValue = payData.getString("package_");
				Log.e("packageValue",req.packageValue);
				req.nonceStr=  payData.getString("noncestr");
				Log.e("nonceStr",req.nonceStr);
				req.timeStamp= payData.getString("timeStamp");
				Log.e("timeStamp",req.timeStamp);
				 req.sign= payData.getString("sign");
				 Log.e("sign",req.sign);
				
				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
	            signParams.add(new BasicNameValuePair("appid", req.appId));
				signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
				signParams.add(new BasicNameValuePair("package", req.packageValue));
				signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
				signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
				signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
				
				req.sign = genAppSign(signParams);
				
				api.sendReq(req);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			
			}		
		
		}
		
		// 二次签名
		private String genAppSign(List<NameValuePair> params) {
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < params.size(); i++) {
				sb.append(params.get(i).getName());
				sb.append('=');
				sb.append(params.get(i).getValue());
				sb.append('&');
			}
			sb.append("key=");
			sb.append(Constants.API_KEY);

			String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		
			return appSign;
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) &&  columnsWebView.canGoBack()) {
			columnsWebView.goBack();
			 return true;
			}else{
				finish();
			}
			return super.onKeyDown(keyCode, event);
		}
}
